package org.epidroid.epidroid.androsoul.widget;

import org.epidroid.epidroid.R;
import org.epidroid.epidroid.androsoul.ui.AndroSoulActivity;

import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.RemoteViews;

public class AndroSoulWidgetProvider extends AppWidgetProvider {

	@Override
	public void onEnabled(Context context) {
		super.onEnabled(context);
	}

	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {

		final int N = appWidgetIds.length;

		for (int i = 0; i < N; i++) {
			updateWidget(context, appWidgetIds[i], appWidgetManager);
		}
	}

	@Override
	public void onDisabled(Context context) {
		context.stopService(new Intent(context, AndroSoulWidgetService.class));
		super.onDisabled(context);
	}

	private void updateWidget(Context context, int appWidgetId,
			AppWidgetManager appWidgetManager) {

		PendingIntent newPending = makeControlPendingIntent(context,
				AndroSoulWidgetService.UPDATE, appWidgetId);
		try {
			newPending.send();
		} catch (CanceledException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Intent intent = new Intent(context, AndroSoulActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
				intent, 0);

		RemoteViews views = new RemoteViews(context.getPackageName(),
				R.layout.androsoul_widget);
		views.setOnClickPendingIntent(R.id.androsoul_widget_login,
				pendingIntent);

		appWidgetManager.updateAppWidget(appWidgetId, views);
	}

	public static PendingIntent makeControlPendingIntent(Context context,
			String command, int appWidgetId) {
		Intent active = new Intent(context, AndroSoulWidgetService.class);
		active.setAction(command);
		active.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
		// this Uri data is to make the PendingIntent unique, so it wont be
		// updated by FLAG_UPDATE_CURRENT
		// so if there are multiple widget instances they wont override each
		// other
		Uri data = Uri.withAppendedPath(
				Uri.parse("androsoulwidget://widget/id/#" + command
						+ appWidgetId), String.valueOf(appWidgetId));
		active.setData(data);
		return (PendingIntent.getService(context, 0, active,
				PendingIntent.FLAG_UPDATE_CURRENT));
	}

}